<script setup lang="ts">
import { ref, reactive, watch, nextTick, computed } from 'vue'
import StratchCard from './scratch-card.vue'
import { cardStyleStore, CardStyle } from './styleStore'
import { handleLhcStyle, handleCommonStyle, NumberItem } from './handleStyle'
import { useGameStore } from '@/stores/game'
import { LotterCodeEnum, GAME_STATUS_CODE } from '@/enum'
import { findHistoryPage } from '@/api'
import { useAppStore } from '@/stores/app'
import handImg from '@/assets/scratch/hand.png'
import { Popup, Icon } from 'vant'

const gameStore = useGameStore(),
  appStore = useAppStore(),
  drawingStatus = computed(() => gameStore.drawingStatus),
  show = ref(false),
  showScratchPopup = ref(false),
  stratchCardDom = ref(''),
  handImgAxis = reactive({ x: 35, y: 25 }),
  disabledShake = ref(false)

let winNumberRenderList: NumberItem[] = reactive([]), //带样式的渲染数据
  winList = ref<string[]>([]), // 较原始的数据
  cardStyle: CardStyle = ref({}) // 刮刮乐卡片样式

// 获取开奖号码
const fetchHistory = async () => {
  let query = {
    current: 1,
    size: 1,
    lotteryCode: gameStore.currentGame,
  }
  const res = await findHistoryPage(query)
  calculateResult(res.data.records[0].drawingResult)
}

// 计算求和
const calculateResult = (result: string) => {
  let arr = result.split(',')
  // 不需要计算的彩种
  const notNeedCalculateGame = [LotterCodeEnum.xglhc, LotterCodeEnum.qxc, LotterCodeEnum.pcnn]
  if (!notNeedCalculateGame.includes(gameStore.currentGame)) {
    arr.push(arr.reduce((arr, curr) => Number(arr) + Number(curr)))
  }
  winList.value = arr.map((number) => number.toString().padStart(2, '0'))
}

// 监听开盘状态
watch(
  drawingStatus,
  async (newValue) => {
    switch (newValue.code * 1) {
      case GAME_STATUS_CODE.mi.code:
        showScratch()
        break
      default:
        closScratch()
        break
    }
  },
  { deep: true },
)

// 显示刮刮乐
const showScratch = async () => {
  if (!appStore.isMipai) return
  await fetchHistory()
  getNumbetStyle()
  cardStyle.value = cardStyleStore[gameStore.currentGame]
  show.value = true
  showScratchPopup.value = show.value

  nextTick(() => {
    stratchCardDom?.value?.reset({ imageUrl: cardStyle?.value?.markImg })
  })
}
// showScratch()
// 不同游戏 处理数字样式
const getNumbetStyle = () => {
  // 不同游戏处理样式map函数
  const styleStoreFn = {
    [LotterCodeEnum.xglhc]: handleLhcStyle,
    common: handleCommonStyle,
  }
  if (Object.prototype.hasOwnProperty.call(styleStoreFn, gameStore.currentGame)) {
    winNumberRenderList = styleStoreFn[gameStore.currentGame](winList.value)
  } else {
    const showDes = gameStore.currentGame === LotterCodeEnum.qxc
    winNumberRenderList = styleStoreFn.common(winList.value, showDes)
  }
}

// 延迟关闭涂层
watch(show, () => {
  if (show.value) {
    handImgAxis.x = 35
    handImgAxis.y = 25
  }
  if (!show.value) {
    setTimeout(() => {
      showScratchPopup.value = false
    }, 300)
  }
})

// 监听开始刮奖
const scratchStart = () => {}
// 监听刮奖结束
const scratchEnd = () => {}
// 监听刮完涂层
const scratchAll = () => {}
// 关闭刮奖
const closScratch = () => {
  // if (show.value) stratchCardDom?.value?.removeMark()
  show.value = false
}
// 监听坐标
const onAxis = (x: number, y: number) => {
  handImgAxis.x = x - 25 //偏移量
  handImgAxis.y = y - 35
}
</script>
<template>
  <Popup v-model:show="show" :overlay="false" style="background: transparent">
    <div class="scratch-popup flex-column" v-if="showScratchPopup">
      <Icon name="cross" color="white" class="close" size="20" @click="closScratch" />
      <img src="@/assets/scratch/title.png" class="title" alt="" />
      <img src="@/assets/scratch/sub-title.png" class="sub-title" alt="" />
      <div class="mark"></div>
      <div class="number-box">
        <StratchCard
          ref="stratchCardDom"
          text="刮一刮"
          :radius="12"
          :scratchRadius="30"
          :imageUrl="cardStyle.markImg"
          :scratchPercent="90"
          @scratchStart="scratchStart"
          @scratchEnd="scratchEnd"
          @scratchAll="scratchAll"
          @onAxis="onAxis"
        >
          <div
            class="item-box row-space-around"
            :class="{ over3: winNumberRenderList?.length > 3, xglhc: LotterCodeEnum.xglhc === gameStore.currentGame }"
            :style="{ backgroundImage: `url(${cardStyle.showImg})`, height: cardStyle.height }"
            ref="winNumber"
          >
            <div class="item column-center" v-for="item in winNumberRenderList" :key="item.number">
              <span class="number all-center" :style="item.numberStyle">{{ item.number }}</span>
              <span class="text all-center" :style="item.desStyle" v-if="item.des">
                {{ item.des }}
              </span>
            </div>
            <transition>
              <img
                v-if="true"
                :class="{ shake: !disabledShake }"
                :src="handImg"
                :style="{ top: `${handImgAxis.y}px`, left: `${handImgAxis.x}px` }"
                class="hand-box"
                alt=""
              />
            </transition>
          </div>
        </StratchCard>
      </div>
    </div>
  </Popup>
</template>
<style lang="less" scoped>
.scratch-popup {
  box-sizing: border-box;
  position: relative;
  width: 300px;
  border-radius: 20px;
  box-shadow: 0px 0px 32px 0px #69111126 inset;
  border: 1px solid #ffffff80;
  align-items: center;
  overflow: hidden;
  background: radial-gradient(
      48.16% 32.59% at 106.66% 56.28%,
      rgba(160, 0, 0, 0.5) 0%,
      rgba(255, 0, 0, 0) 100%,
      rgba(255, 194, 194, 0) 100%
    ),
    linear-gradient(180deg, #ff5656 0%, #e72323 79.41%),
    linear-gradient(0deg, rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)),
    radial-gradient(49.58% 29.44% at -12.32% -0.99%, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0) 100%);

  &::after {
    content: '';
    position: absolute;
    bottom: 5px;
    width: 100%;
    height: 100%;
    border: 1px solid white;
    border-radius: 20px;
    pointer-events: none;
  }

  .close {
    position: absolute;
    right: 12px;
    top: 12px;
  }

  .title {
    width: 248.24px;
    height: 45.87px;
  }

  .sub-title {
    margin-top: 15px;
    width: 250px;
    height: 53px;
  }

  .mark {
    position: absolute;
    top: 120px;
    left: 0;
    width: 100%;
    height: 236px;
    border-top-left-radius: 35% 5%;
    border-top-right-radius: 35% 5%;
    background: linear-gradient(180deg, rgba(255, 166, 147, 0.3) 40.13%, rgba(255, 224, 217, 0) 66.95%);
  }

  .number-box {
    box-sizing: border-box;
    position: relative;
    font-weight: 600;
    margin: 30px 0 30px 0;
    border-radius: 12px;
    overflow: hidden;
    cursor: none;

    .watermark {
      position: absolute;
      max-width: auto;
      height: 100%;
    }

    .item-box {
      box-sizing: border-box;
      position: relative;
      display: flex;
      flex-wrap: wrap;
      background: white;
      border-radius: 12px;
      width: 276px;
      padding: 14px 15px;
      align-items: center;
      background-size: 100% 100%;
      background-repeat: no-repeat;

      .shake {
        animation: shake 1s linear 2;
      }

      @keyframes shake {
        25% {
          transform: translateY(-15px);
        }

        75% {
          transform: translateY(15px);
        }

        0%,
        50%,
        100% {
          transform: translateY(0);
        }
      }

      .hand-box {
        position: absolute;
        pointer-events: none;
        width: 101px;
        height: 115px;
        z-index: 9999;
      }

      &.over3 {
        .item:nth-last-of-type(1) {
          .number {
            color: rgba(254, 92, 115, 1);
            background: url('@/assets/img/game/win_number_result_bg.png') center center no-repeat;
            background-size: contain;
          }
        }
      }

      &:not(.xglhc) {
        .item {
          background: url('@/assets/img/game/win_number_result_blue.png') center center no-repeat;
          background-size: contain;
        }
      }

      .item {
        position: relative;
        box-sizing: border-box;
        width: calc(33.33% - 25px);
        margin: 5px;

        .number {
          width: 45px;
          height: 45px;
          border-radius: 50%;
          color: rgba(105, 80, 255, 1);
          font-size: 24px;
        }

        .text {
          position: absolute;
          bottom: -16px;
          color: #008ddc;
          font-size: 14px;
        }
      }
    }
  }
}
</style>
